package cn.ciis.sys.account;

import cn.ciis.basic.auth.AdminAuthService;
import cn.ciis.basic.base.BaseController;
import cn.ciis.basic.kit.CiisKit;
import cn.ciis.basic.model.Account;
import cn.ciis.basic.model.Role;
import cn.ciis.ciis.enterprise.EnterpriseAdminService;
import cn.ciis.sys.login.LoginService;
import cn.ciis.sys.permission.Notes;
import cn.ciis.sys.permission.Remark;
import cn.ciis.sys.role.RoleAdminService;
import com.jfinal.aop.Before;
import com.jfinal.aop.Inject;
import com.jfinal.kit.HashKit;
import com.jfinal.kit.Ret;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.ehcache.CacheKit;

import java.util.Date;
import java.util.List;

/**
 * 账户管理控制器
 *
 * @author 冉志林
 */
public class AccountAdminController extends BaseController {

    @Inject
    AccountAdminService srv;

    @Inject
    RoleAdminService roleAdminSrv;

    @Inject
    AdminAuthService adminAuthService;

    @Inject
    EnterpriseAdminService enterpriseAdminService;


    @Notes(value = "账户管理")
    @Remark(value = "账户列表")
    public void index() {
        Account mode = getModel(Account.class, "", true);
        srv.getFieldAndNotes();
        boolean b = adminAuthService.isSuperAdmin(getLoginAccountId());
        if (!b) {
            if (getLoginAccount().getEId()>1){
                mode.set("eid",getLoginAccount().getEId());
            }

        }
        kModel(mode, srv.paginate(getInt(PAGENUMBER, 1), getInt(PAGESIZE, 10), mode));
    }

    @Remark(value = "账户添加或编辑页")
    public void addOrEdit(Integer id) {
        set("enterpriseList",enterpriseAdminService.findAll());
        kAddOrEdit(srv.findById(id));
    }

    @Remark(value = "账户保存或修改")
    @Before(AccountUpdateValidator.class)
    public void saveOrUpdate() {
        Account bean = getBean(Account.class);
        if (StrKit.notBlank(bean.getPassword())) {
            String salt = HashKit.generateSaltForSha256();
            bean.setSalt(salt);
            bean.setPassword(HashKit.sha256(salt + bean.getPassword()));
            bean.setCreateAt(new Date());
            bean.setIp(CiisKit.getRealIp(getRequest()));
            bean.setAvatar("0/1.jpg");
        }
        String mobile = bean.getMobile();
        String email = bean.getEmail();
        String userName = bean.getUserName();
        int accountId = getLoginAccountId();
        boolean mobile1 = srv.isNull("mobile", mobile, accountId);
        if (mobile1) {
            renderJson(Ret.fail("msg", "手机号重复！"));
            return;
        }
        boolean email1 = srv.isNull("email", email, accountId);
        if (email1) {
            renderJson(Ret.fail("msg", "邮箱号重复！"));
            return;
        }
        boolean userName1 = srv.isNull("userName", userName, accountId);
        if (userName1) {
            renderJson(Ret.fail("msg", "登录名重复！"));
            return;
        }
        renderJson(srv.saveOrUpdate(bean));
    }

    @Remark(value = "账户删除")
    public void deletes(String ids) {
        String[] split = ids.split(",");
        boolean b = useLoop(split, String.valueOf(getLoginAccountId()));
        if (b) {
            renderJson(Ret.fail("msg", "用户不能删除或拉黑自己"));
            return;
        }
        for (String s : split) {
            // 删除用户所有角色
            srv.deleteRole(s);
        }
        renderJson(srv.deletes(ids));
    }

    @Remark(value = "账户锁定")
    public void lock() {
        Ret ret = srv.lock(getLoginAccountId(), getParaToInt("id"));
        renderJson(ret);
    }

    @Remark(value = "账户解锁")
    public void unlock() {
        Ret ret = srv.unlock(getParaToInt("id"));
        renderJson(ret);
    }


    @Remark(value = "账户分配角色页")
    public void assignRoles() {
        Account account = (Account) srv.findById(getParaToInt("id"));
        boolean b = adminAuthService.isSuperAdmin(getLoginAccountId());
        List<Role> roleList = roleAdminSrv.getAllRoles(b);
        srv.markAssignedRoles(account, roleList);

        setAttr("model", account);
        setAttr("roleList", roleList);
        render("assign_roles.html");
    }

    @Remark(value = "添加角色")
    public void addRole() {
        Ret ret = srv.addRole(getParaToInt("accountId"), getParaToInt("roleId"));
        renderJson(ret);
    }

    @Remark(value = "删除角色")
    public void deleteRole() {
        Ret ret = srv.deleteRole(getParaToInt("accountId"), getParaToInt("roleId"), getLoginAccountId());
        renderJson(ret);
    }


    @Remark(value = "修改头像页面")
    public void avatar(int id) {
        // 保持住分页的页号，便于在 ajax 提交后跳转到当前数据所在的页
        keepPara("p").keepPara("s");
        setAttr("model", srv.findById(id));
        render("avatar.html");
    }

    @Remark(value = "上传头像图片")
    public void uploadImg() {
        kUploadFile("avatar","avatar",1024*1024,300);
    }

    @Remark(value = "保存头像图片")
    public void saveImg(int id) {
        Account Account = (Account)srv.findById(id);
        CacheKit.removeAll(LoginService.LOGIN_ACCOUNT_CACHE_NAME);
        CacheKit.put(LoginService.LOGIN_ACCOUNT_CACHE_NAME, StrKit.getRandomUUID(), Account);
        kSaveImg(Account,"avatar",srv.getTable(),"avatar");
    }

    @Remark(value = "个人密码修改")
    public void updatePassword(Integer id) {
        if (id!=null) {
            set("model", srv.findById(id));
            render("update_password.html");
        }
    }
}
